package cn.huhst.cas.weisiqian.dbhelp;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;

public class DBHelper {

	private static Logger logger = Logger.getLogger(DBHelper.class);
	private static String driver = null;
	private static String url = null;
	private static String username = null;
	private static String password = null;

	static {
		ResourceBundle rb = ResourceBundle.getBundle("db");
		driver = rb.getString("Driver");
		url = rb.getString("Url");
		username = rb.getString("Username");
		password = rb.getString("Password");
	}

	/**
	 * 获取数据库连接
	 * 
	 * @return
	 */
	public static Connection getConnection() {
		Connection conn = null;
		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			logger.error("没有找到mysql数据库驱动", e);
		}
		try {
			conn = DriverManager.getConnection(url, username, password);
		} catch (SQLException e) {
			logger.error("创建数据库连接失败", e);
		}
		return conn;
	}

	public static void closeConnection(Connection conn) {
		try {
			if (conn != null && !conn.isClosed()) {
				conn.close();
			}
		} catch (SQLException e) {
			logger.error("关闭Connection出错", e);
		}
	}

	public static void closePreparedStatement(PreparedStatement pstmt) {
		try {
			if (pstmt != null && !pstmt.isClosed()) {
				pstmt.close();
			}
		} catch (SQLException e) {
			logger.error("关闭PreparedStatement出错", e);
		}
	}

	public static void closeStatement(Statement stmt) {
		try {
			if (stmt != null && !stmt.isClosed()) {
				stmt.close();
			}
		} catch (SQLException e) {
			logger.error("关闭Statement出错", e);
		}
	}

	public static void closeResultSet(ResultSet rs) {
		try {
			if (rs != null && !rs.isClosed()) {
				rs.close();
			}
		} catch (SQLException e) {
			logger.error("关闭Result出错", e);
		}
	}

	public static void closeDBHelp(Connection conn, Statement stmt, ResultSet rs) {
		closeResultSet(rs);
		closeStatement(stmt);
		closeConnection(conn);
	}

	public static void closeDBHelp(Connection conn, PreparedStatement pstmt, ResultSet rs) {
		closeResultSet(rs);
		closePreparedStatement(pstmt);
		closeConnection(conn);
	}
}
